package com.jiangyg.mall.core;

import com.jiangyg.mall.core.support.web.WebFluxExceptionHandler;
import com.jiangyg.mall.core.utils.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
 * 类描述：REACTIVE 服务配置
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-10-13
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class WebFluxAutoConfiguration {

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    public WebFluxAutoConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                    ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(-2)
    public WebFluxExceptionHandler reactiveWebExceptionHandler() {
        Logger.info(log, () -> "[项目启动] - 注册 ReactiveWebExceptionHandler 异常处理……");
        return new WebFluxExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

}
